package com.alander.nexusgo.itinerary.controller;

import com.alibaba.cloud.ai.dashscope.agent.DashScopeAgent;
import com.alibaba.cloud.ai.dashscope.api.DashScopeAgentApi;
import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/ai")
@Slf4j
public class BailianAgentController {

    private DashScopeAgent agent;

    @Value("${spring.ai.dashscope.agent.app-id}")
    private String appId;

    @Value("${spring.ai.dashscope.api-key}")
    private String apiKey;

    public BailianAgentController(DashScopeAgentApi dashscopeAgentApi) {
        this.agent = new DashScopeAgent(dashscopeAgentApi);
    }

    @GetMapping("/bailian/agent/call")
    public Flowable<ApplicationResult> call(@RequestParam(value = "city") String city,
                       @RequestParam(value = "days") String days,
                       @RequestParam(value = "interests") String interests,
                       @RequestParam(value = "budgetRange") String budgetRange) throws NoApiKeyException, InputRequiredException {

        String bizParams = "{\"city\":\"" + city + "\",\"days\":\"" + days + "\",\"interests\":\"" + interests + "\",\"budgetRange\":\"" + budgetRange + "\"}";
        String prompt = "请根据以下信息生成旅游计划：城市=" + city + "，天数=" + days + "，兴趣=" + interests + "，预算=" + budgetRange;

        ApplicationParam param = ApplicationParam.builder()
                .appId(appId)
                .apiKey(apiKey)
                .prompt(prompt)
                .bizParams(JsonUtils.parse(bizParams))
                .build();

        Application application = new Application();
        Flowable<ApplicationResult> result = application.streamCall(param);
        result.blockingForEach(data -> {
            System.out.printf("%s\n",
                    data.getOutput().getText());
        });
        return result;
    }
}